import Koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import cors from '@koa/cors'
import { DataTypes, Sequelize, Op } from 'sequelize'

const app = new Koa()
const router = new Router()

app.use(cors())
app.use(bodyParser())

const sequelize = new Sequelize('bookdb', 'root', '123456', {
    dialect: 'mysql',
    host: 'localhost'
})

const Book = sequelize.define('books', {
    bookName: DataTypes.STRING,
    author: DataTypes.STRING
})

await sequelize.sync()

router.get('/book', async (ctx) => {
    const keyword = ctx.request.query.keyword || ''
    let bookList
    if (keyword) {
        bookList = await Book.findAll({
            where: {
                [Op.or]: {
                    bookName: { [Op.like]: `%${keyword}%` },
                    author: { [Op.like]: `%${keyword}%` }
                }
            }
        })
    } else {
        bookList = await Book.findAll()
    }

    ctx.body = {
        code: 200,
        msg: '成功',
        data: bookList
    }

})
router.get('/book/:id', async (ctx) => {
    const id = ctx.request.params.id || 0
    const book = await Book.findByPk(id)
    ctx.body = {
        code: 200,
        msg: '成功',
        data: book
    }
})
router.post('/book', async (ctx) => {
    const bookObj = ctx.request.body
    const book = await Book.create(bookObj)
    ctx.body = {
        code: 200,
        msg: '成功',
        data: book
    }

})
router.put('/book/:id', async (ctx) => {
    const id = ctx.request.params.id || 0
    const bookObj = ctx.request.body
    const book = await Book.update(bookObj, { where: { id } })
    ctx.body = {
        code: 200,
        msg: '成功',
        data: book
    }
})
router.delete('/book/:id', async (ctx) => {
    const id = ctx.request.params.id || 0
    const book = await Book.destroy({ where: { id } });
    ctx.body = {
        code: 200,
        msg: '成功',
        data: book
    }
})

app.use(router.routes())

app.listen(8000)
console.log('http://localhost:8000');